<?php
/**
 * 后台用户管理控制器
 */

namespace App\HttpController\Admin;

use App\Model\Adm;
use App\Model\SysErrLog;
use App\Util\Common;
use EasySwoole\Http\Exception\Exception;

class Admin extends Base
{
    public function index(){
        $limit = Common::limit($this->request());
        $key = $this->request()->getQueryParam('key');
        $mode = Adm::create()->limit(...$limit)->order('id')->withTotalCount();
        $mode->field('id,phone,name,status,group_id,last_login_time,create_time')->with('grp');
        if($key){
            if(is_numeric($key)){
                $mode->where('phone',$key);
            } else {
                $mode->where('name',"%{$key}%",'like');
            }
        }
        $data = $mode->all();
        $rows = $mode->lastQueryResult()->getTotalCount();
        $this->lay($data,$rows);
    }

    /**
     * 保存一个后台用户的修改或新增
     */
    public function save(){
        $data = Common::check($this->request(),'data','post');
        $mode = Adm::create();
        if( !isset($data['password']) ||  !$data['password'] ){
            unset($data['password']);
        }
        if( !isset($data['password']) && !$data['id'] )
            throw new Exception('密码不能为空！',403);

        if(isset($data['id']) && $data['id'] > 0){
            $ret = $mode->update($data);
        } else {
            unset($data['id']);
            $ret = $mode->data($data)->save();
        }
        if($ret ){
            $this->success(['data'=>$ret]);
        } else {
            throw new Exception('save admin user fail', 403);
        }
    }

    public function del(){
        $id = Common::check($this->request(),'id');
        $ret = Adm::create()->get($id);
        if(!$ret) throw new Exception('参数错误！',403);
        $ret->destroy();
        $this->success();
    }

    public function syserr(){
        $data = Common::adv_list($this->request(),SysErrLog::class);
        $this->lay(...$data);
    }

    public function del_syserr(){
        $ids = Common::check($this->request(),'ids','POST');
        SysErrLog::create()->destroy($ids);
        $this->success();
    }
}